package com.xiaowei.gym.gymjsp.ware.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.mysql.cj.util.StringUtils;
import com.xiaowei.gym.gymjsp.ware.entity.MemberEntity;
import com.xiaowei.gym.gymjsp.ware.entity.PersonnelEntity;
import com.xiaowei.gym.gymjsp.ware.entity.ReservationEntity;
import com.xiaowei.gym.gymjsp.ware.entity.SalaryEntity;
import com.xiaowei.gym.gymjsp.ware.service.MemberService;
import com.xiaowei.gym.gymjsp.ware.service.ReservationService;
import com.xiaowei.gym.gymjsp.ware.service.impl.MemberServiceImpl;
import com.xiaowei.gym.gymjsp.ware.service.impl.ReservationServiceImpl;
import com.xiaowei.gym.gymjsp.ware.util.Constants;
import com.xiaowei.gym.gymjsp.ware.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@WebServlet({"/gymjsp/member.do","/gymjsp/reservation.do"})
public class MemberServlet extends HttpServlet {

    private MemberService memberService;

    private ReservationService reservationService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        String servletPath = req.getServletPath();
        if (servletPath!=null && servletPath.equals("/gymjsp/member.do")){
            if (method!=null && method.equals("query")){
                this.memberquery(req,resp);
            }else if (method!=null && method.equals("view")){
                this.getMemberById(req,resp,"member/memberview.jsp");
            }else if(method != null && method.equals("modify")){
                this.getMemberById(req,resp,"member/membermodify.jsp");
            }else if (method != null && method.equals("delmember")){
                this.delmember(req,resp);
            }else if (method != null && method.equals("add")){
                this.addMeber(req,resp);
            }else if (method != null && method.equals("view")){
                this.getMemberById(req,resp,"member/memberview.jsp");
            }else if (method != null && method.equals("modifyexe")){
                this.membermodify(req,resp);
            }
        }else if (servletPath!=null && servletPath.equals("/gymjsp/reservation.do")){
                if (method != null && method.equals("query")){
                    this.resevationquery(req,resp);
                }else if (method != null && method.equals("add")){
                    try {
                        this.addReservation(req,resp);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }else if (method != null && method.equals("modify")){
                    this.getReservationByid(req,resp,"member/reservationmodify.jsp");
                }else if(method != null && method.equals("getAll")){
                    this.getAll(req,resp);
                }else if (method != null && method.equals("modifyexe")){
                    try {
                        this.reservationmodify(req,resp);
                    }catch (ParseException p){
                        p.printStackTrace();
                    }
                }else if (method != null && method.equals("delresevation")){
                    this.delresevation(req,resp);
                }else if (method != null && method.equals("view")){
                    this.getReservationByid(req,resp,"member/reservationview.jsp");
                }
        }
    }

    private void membermodify(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String mid = req.getParameter("mid");
        String name = req.getParameter("membername");
        String gender = req.getParameter("gender");
        String age = req.getParameter("age");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setId(Integer.valueOf(mid));
        memberEntity.setName(name);
        memberEntity.setGender(gender);
        memberEntity.setAge(Integer.valueOf(age));
        memberEntity.setPhone(phone);
        memberEntity.setAddress(address);
        if (memberService.modify(memberEntity)){
            resp.sendRedirect(req.getContextPath() + "/gymjsp/member.do?method=query");
        }else {
            req.getRequestDispatcher("member/membermodify.jsp").forward(req, resp);
        }
    }

    private void getMemberById(HttpServletRequest req, HttpServletResponse resp, String url) throws ServletException, IOException {

        String mid = req.getParameter("mid");
        if (!StringUtils.isNullOrEmpty(mid)){
            MemberEntity  memberEntity = memberService.getMemberById(Integer.valueOf(mid));
            req.setAttribute("member",memberEntity);
            req.getRequestDispatcher(url).forward(req, resp);
        }
    }

    private void delresevation(HttpServletRequest request,HttpServletResponse resp) throws IOException {
        String id = request.getParameter("rid");
        System.out.println("获取到的id:"+id);
        String[] ids = JSON.parseObject(id,String[].class);
        Integer[] delId = new Integer[ids.length];
        try {
            delId = Arrays.stream(ids)
                    .mapToInt(Integer::parseInt)
                    .boxed()
                    .toArray(Integer[]::new);
            System.out.println("delId长度:"+delId.length);
            System.out.println("delId:"+delId.toString());
        } catch (Exception e) {
            // TODO: handle exception
            delId[0] = 0;
        }
        HashMap<String, String> resultMap = new HashMap<>();
        if (delId.length <= 0 ) {
            resultMap.put("delResult", "notexist");
        } else {
            if (reservationService.delreservationByIds(delId)) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }
        //把resultMap转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        Gson gson = new Gson();
        outPrintWriter.write(gson.toJson(resultMap));
        outPrintWriter.flush();
        outPrintWriter.close();
    }

    private void reservationmodify(HttpServletRequest request, HttpServletResponse resp) throws ParseException{
        String rid = request.getParameter("rid");
        String reservedTime = request.getParameter("reserved_time");
        String remarks = request.getParameter("remarks");
        ReservationEntity reservationEntity = new ReservationEntity();
        reservationEntity.setId(Integer.valueOf(rid));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String[] timeParts = reservedTime.split("T");
        String formatTime = timeParts[0] + " " + timeParts[1];
        reservationEntity.setReserved_time(simpleDateFormat.parse(formatTime));
        reservationEntity.setRemarks(remarks);
        System.out.println(reservationEntity);
        if (reservationService.modify(reservationEntity)) {
            try {
                resp.sendRedirect(request.getContextPath() + "/gymjsp/reservation.do?method=query");
            }catch (IOException ioException){
                ioException.printStackTrace();
            }
        } else {
            try {
                request.getRequestDispatcher("member/reservationmodify.jsp").forward(request, resp);
            }catch (Exception servletException){
                servletException.printStackTrace();
            }

        }
    }

    private void getReservationByid(HttpServletRequest req, HttpServletResponse resp, String url) throws ServletException, IOException {
        String rid = req.getParameter("rid");
        if (!StringUtils.isNullOrEmpty(rid)){
            ReservationEntity  reservationEntity = reservationService.getReservationById(Integer.valueOf(rid));
            req.setAttribute("reservation",reservationEntity);
            req.getRequestDispatcher(url).forward(req, resp);
        }
    }

    private void addReservation(HttpServletRequest req, HttpServletResponse resp) throws ParseException, IOException, ServletException {

        String memberId = req.getParameter("memberId");
        String reseredTime = req.getParameter("reserved_time");
        String remarks = req.getParameter("remarks");
        ReservationEntity reservationEntity = new ReservationEntity();
        reservationEntity.setMember_id(Integer.valueOf(memberId));
        String[] timeParts = reseredTime.split("T");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String reserTime = timeParts[0] + " "+timeParts[1];
        reservationEntity.setReserved_time(simpleDateFormat.parse(reserTime));
        reservationEntity.setRemarks(remarks);
        if (reservationService.addReservation(reservationEntity)){
            resp.sendRedirect(req.getContextPath() + "/gymjsp/reservation.do?method=query");
        }else {
            req.getRequestDispatcher("member/reservationadd.jsp").forward(req, resp);
        }
    }

    private void getAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<MemberEntity> memberEntityList = memberService.getMemberlAll();
        //把providerList转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(memberEntityList));
        outPrintWriter.flush();
        outPrintWriter.close();
    }

    private void resevationquery(HttpServletRequest request, HttpServletResponse resp) throws IOException, ServletException {

        //从前端获取数据
        String member_id = request.getParameter("member_id");
//        String temp = request.getParameter("queryUserRole");
        String pageIndex = request.getParameter("pageIndex");
        int queryUserRole = 0;
        List<ReservationEntity> reservationEntityList = null;
        //第一次走这个请求，一定是第一页，页面大小是固定的
        //设置页面容量
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize") == null ? String.valueOf(Constants.pageSize) : request.getParameter("pageSize"));
        if (pageSize == null){
            pageSize = Constants.pageSize;
        }
        //默认当前页码
        int currentPageNo = 1;
        if (StringUtils.isNullOrEmpty(member_id)) {
            member_id = "-1";
        }

        if (pageIndex != null) {
            try {
                currentPageNo = Integer.valueOf(pageIndex);
            } catch (NumberFormatException e) {
                resp.sendRedirect("gymjsp/error.jsp");
            }
        }
        //总数量（表）
        int i = reservationService.getCount();
        int totalCount = i;
        //总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);  //当前页
        pages.setPageSize(pageSize);            //页面大小
        pages.setTotalCount(totalCount);        //总数量

        int totalPageCount = pages.getTotalPageCount();  //总页面数量

        //控制首页和尾页
        //如果页面小于第一页，就显示第一页
        if (currentPageNo < 1) {
            currentPageNo = 1;
            //如果当前页面大于最后一页，当前页等于最后一页即可
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }

        //获取员工信息列表展示
        reservationEntityList = reservationService.getResevationList(Integer.valueOf(member_id)<0?0:Integer.valueOf(member_id) , currentPageNo, pageSize);
        System.out.println(reservationEntityList);
        request.setAttribute("reservationList",reservationEntityList);
        request.setAttribute("member_id",member_id.equals("-1") ? "" : member_id);
        request.setAttribute("queryUserRole", queryUserRole);
        request.setAttribute("totalPageCount", totalPageCount);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("pageSize",pageSize);
        request.setAttribute("currentPageNo", currentPageNo);
        request.getRequestDispatcher("member/reservation.jsp").forward(request,resp);
    }

    private void delmember(HttpServletRequest request, HttpServletResponse resp) throws IOException {
        String id = request.getParameter("pid");
        System.out.println("获取到的id:"+id);
        String[] ids = JSON.parseObject(id,String[].class);
        Integer[] delId = new Integer[ids.length];
        try {
            delId = Arrays.stream(ids)
                    .mapToInt(Integer::parseInt)
                    .boxed()
                    .toArray(Integer[]::new);
            System.out.println("delId长度:"+delId.length);
            System.out.println("delId:"+delId.toString());
        } catch (Exception e) {
            // TODO: handle exception
            delId[0] = 0;
        }
        HashMap<String, String> resultMap = new HashMap<>();
        if (delId.length <= 0 ) {
            resultMap.put("delResult", "notexist");
        } else {
            if (memberService.deleteMemberByIds(delId)) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }
        //把resultMap转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        Gson gson = new Gson();
        outPrintWriter.write(gson.toJson(resultMap));
        outPrintWriter.flush();
        outPrintWriter.close();
    }

    private void addMeber(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String name = req.getParameter("membername");
        String age = req.getParameter("age");
        String gender = req.getParameter("gender");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String card_number = req.getParameter("card_number");

        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setName(name);
        memberEntity.setAge(Integer.valueOf(age));
        memberEntity.setGender(gender);
        memberEntity.setPhone(phone);
        memberEntity.setAddress(address);
        memberEntity.setCard_number(card_number);
        memberEntity.setCreate_date(new Date());
        if (memberService.addMember(memberEntity)){
            resp.sendRedirect(req.getContextPath() + "/gymjsp/member.do?method=query");
        }else {
            req.getRequestDispatcher("member/memberadd.jsp").forward(req, resp);
        }

    }

    private void memberquery(HttpServletRequest request, HttpServletResponse resp) throws IOException, ServletException {

        //从前端获取数据
        String name = request.getParameter("name");
//        String temp = request.getParameter("queryUserRole");
        String pageIndex = request.getParameter("pageIndex");
        int queryUserRole = 0;
        List<MemberEntity> memberEntityList = null;
        //第一次走这个请求，一定是第一页，页面大小是固定的
        //设置页面容量
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize") == null ? String.valueOf(Constants.pageSize) : request.getParameter("pageSize"));
        if (pageSize == null){
            pageSize = Constants.pageSize;
        }
        //默认当前页码
        int currentPageNo = 1;

        if (name == null) {
            name = "";
        }

        if (pageIndex != null) {
            try {
                currentPageNo = Integer.valueOf(pageIndex);
            } catch (NumberFormatException e) {
                resp.sendRedirect("gymjsp/error.jsp");
            }
        }
        //总数量（表）
        int i = memberService.getCount();
        int totalCount = i;
        //总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);  //当前页
        pages.setPageSize(pageSize);            //页面大小
        pages.setTotalCount(totalCount);        //总数量

        int totalPageCount = pages.getTotalPageCount();  //总页面数量

        //控制首页和尾页
        //如果页面小于第一页，就显示第一页
        if (currentPageNo < 1) {
            currentPageNo = 1;
            //如果当前页面大于最后一页，当前页等于最后一页即可
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }

        //获取员工信息列表展示
        memberEntityList = memberService.getMemberList(name, currentPageNo, pageSize);
        request.setAttribute("member",memberEntityList);
        request.setAttribute("name",name);
        request.setAttribute("queryUserRole", queryUserRole);
        request.setAttribute("totalPageCount", totalPageCount);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("pageSize",pageSize);
        request.setAttribute("currentPageNo", currentPageNo);
        request.getRequestDispatcher("member/member.jsp").forward(request,resp);
    }

    @Override
    public void init() throws ServletException {
        memberService = new MemberServiceImpl();
        reservationService = new ReservationServiceImpl();
    }
}
